package cn.fetosoft.woodpecker.core.jmeter.element.listener;

import cn.fetosoft.woodpecker.core.data.entity.BaseCollector;
import cn.fetosoft.woodpecker.core.data.entity.BaseElement;
import cn.fetosoft.woodpecker.core.data.service.ReportService;
import cn.fetosoft.woodpecker.core.jmeter.collector.AggregateReportCollector;
import cn.fetosoft.woodpecker.core.jmeter.element.AbstractElementBuild;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.samplers.SampleSaveConfiguration;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 创建聚合报告
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/6/30 16:06
 */
@Component("aggregateReportImpl")
public class CreateAggregateReportImpl extends AbstractElementBuild {

	private static final Logger logger = LoggerFactory.getLogger(CreateAggregateReportImpl.class);
	private final static String JMETER_PATH =  System.getProperty("user.dir") + "/jmeter";
	@Autowired
	private ReportService reportService;

	@Override
	protected TestElement convert(BaseElement be) throws Exception {
		BaseCollector collector = (BaseCollector) be;
		//增加结果收集
		Summariser summer = null;
		String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
		if (summariserName.length() > 0) {
			summer = new Summariser(summariserName);
		}
		AggregateReportCollector report = new AggregateReportCollector(summer, aggregateReport -> {
			try{
				if(StringUtils.isNotBlank(aggregateReport.getPlanId())) {
					reportService.insert(aggregateReport);
				}
			}catch(Exception e){
				logger.error("report Callback", e);
			}
		});
		report.setProperty(TestElement.TEST_CLASS, ResultCollector.class.getName());
		report.setErrorLogging(collector.isErrorLogging());
		//输出测试报告
		//report.setFilename(JMETER_PATH + "/report/" + be.getTestId() + ".csv");
		SampleSaveConfiguration saveConfiguration = new SampleSaveConfiguration();
		report.setSaveConfig(saveConfiguration);
		return report;
	}
}
